import axios from 'axios'
import { Result } from '@/utils/http/types'
import type {
  AxiosInstance,
  AxiosResponse,
  AxiosRequestConfig,
  InternalAxiosRequestConfig
} from 'axios'

const instance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL
})

instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  return config
})

instance.interceptors.response.use(
  (response: AxiosResponse<Result>) => {
    if (!response?.data) {
      return Promise.reject(response)
    }
    if (response.request.type === 'blob') {
      return response.data
    }
    return response.data.data
  },
  (error) => {
    console.log(error)
  }
)

const request = <T = any, R = any>(config: AxiosRequestConfig<T>) => {
  return instance<T, R>(config)
}

export default {
  get: async <R = any>(option: AxiosRequestConfig) => {
    return await request<any, R>(option)
  }
}
